#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
This program draws contour map of the entropy
''' 

import common
import os
import numpy as np
import math
import scipy
import matplotlib.pyplot
import matplotlib.mlab as mlab
import sys

path = os.path.join("..", "results", "two_d_triang", "J_1.0")

dT = 'dT0.05'

bList = os.listdir(path)
bList = [eval(tB.replace('B_', '')) for tB in bList]
bList.sort()
bList = bList[1:]

def Entropy(T, E):
    '''
    returns entropy
    '''
    beta = [1 / tt for tt in T]
    S = []
    for i in xrange(len(E)):
        S += [ math.log(2) + E[i] / T[i] + scipy.trapz(E[i:], beta[i:]) ]
        
    minS = min(S)
    return [ts - minS for ts in S]    

#matplotlib.pyplot.plot(T, S4, "*", label = "$S = S(\infty) + E(T) / T - \int_{(1/T)}^{0} E(1/T) d (1/T)$")
    
ttList = os.listdir( os.path.join(path, 'B_' + str(bList[0]), 'N10', dT, 'Energy_J') )

Z = np.zeros( shape = (len(ttList), len(bList)) )

for tb, B in enumerate(bList):
    tList = []
    Energy = []
    result = []
    
    for T in os.listdir( os.path.join(path, 'B_' + str(bList[0]), 'N10', dT, 'Energy_J') ):
        E_J = eval(open(os.path.join(path, 'B_' + str(bList[0]), 'N10', dT, 'Energy_J', T)).read())
        E_B = eval(open(os.path.join(path, 'B_' + str(bList[0]), 'N10', dT, 'Energy_B', T)).read())
        
        result += [ (eval(T.replace('T', '')), E_J + E_B) ]
        #Energy += [ E_J + E_B ]
        #tList += [ eval(T.replace('T', '')) ]
    
    result.sort()
    
    tList = [tx[0] for tx in result]
    Energy = [tx[1] for tx in result]
    
    S = Entropy( tList, Energy )
    for i in xrange(len(S)):
        T = tList[i]
        #result[ (tB, T) ] = S[i]
        Z[(i, tb)] = S[ i ]


#print Z
        
print 'len tList', len(tList)
print 'len blist', len(bList)
print Z
CS = matplotlib.pyplot.contour(bList, tList, Z)
matplotlib.pyplot.clabel(CS, inline=1, fontsize=10)
matplotlib.pyplot.show()